﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NServiceBus;

namespace DHJ.Cost.Web.Startup
{
    public static class NServicebusServiceCollectionExtensions
    {
        public static void ConfigureNServicebus(this IServiceCollection services, NServicebusOptions nServicebusOptions)
        {
            var endpointConfiguration = new EndpointConfiguration(nServicebusOptions.EndpointName);
            var transport = endpointConfiguration.UseTransport<RabbitMQTransport>();

            transport.UseConventionalRoutingTopology();

            transport.ConnectionString(nServicebusOptions.RabbitMqConnectionString);
            endpointConfiguration.SendFailedMessagesTo(nServicebusOptions.EndpointName + "_error");
            endpointConfiguration.EnableInstallers();

            var endpoint = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();
            //var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
            services.AddSingleton<IEndpointInstance>(endpoint);
        }
    }

    public class NServicebusOptions
    {
        public NServicebusOptions()
        {

        }

        public string EndpointName { get; set; }

        public string RabbitMqConnectionString { get; set; }
    }
}
